package com.banciyuan.bcywebview.biz.circles.fragment.list;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpecialApi;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.topic.TopicDetailActivity;
import com.banciyuan.bcywebview.biz.topic.TopicDetailListAdapter;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Special;

/**
 * Created by squall on 2016/4/29.
 */
public class CircleListTopicFragment extends CircleListBaseFragment {


    private TopicDetailListAdapter topicDetailListAdapter;
    private PullToRefreshListView mRefreshLv;
    private ListView mListview;
    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;
    private RequestQueue queue;
    private List<Special> slist = new ArrayList<>();

    private int page = 1;
    private boolean is_load = false;
    private boolean is_end = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.circletopic_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        initData();
        return rootView;
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshLv = (PullToRefreshListView) rootview.findViewById(R.id.listView);
        mListview = mRefreshLv.getRefreshableView();
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        getTopic();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_load && !is_end) {
                    page++;
                    initData();
                }
            }
        });

        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_load = false;
                is_end = false;
                page = 1;
                initData();
            }
        });

        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = position - 1;
                if (index < 0 || index >= slist.size()) return;
                gotoUtil.gotoAct(getActivity(), TopicDetailActivity.class, slist.get(position - 1).getSpecial_id());
            }
        });
    }

    private void getTopic() {
        String url = HttpUtils.BASE_URL + SpecialApi.getSpecials();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair(HttpUtils.TYPE, "circle"));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<Special> templist = gson.fromJson(result, new TypeToken<List<Special>>() {
                        }.getType());
                        renderData(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }


    private void renderData(List<Special> templist) {
        if (page == 1) {
            slist.clear();
        }
        if (templist.size() == 0) {
            is_end = true;
        }
        slist.addAll(templist);
        if (topicDetailListAdapter == null) {
            topicDetailListAdapter = new TopicDetailListAdapter(slist, getActivity());
            mListview.setAdapter(topicDetailListAdapter);
        } else {
            topicDetailListAdapter.notifyDataSetChanged();
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

}
